package com.chinaisafe.user.service.impl;

import com.chinaisafe.module.user.request.SysRoleReqVO;
import com.chinaisafe.module.user.response.SysRoleRespVO;
import com.chinaisafe.user.entity.SysRole;
import com.chinaisafe.user.mapper.SysRoleMapper;
import com.chinaisafe.user.service.SysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.chinaisafe.base.common.exception.BizException;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaisafe.base.mybatisplus.util.MpQueryWrapperPageUtil;

import java.util.Arrays;
import java.util.Optional;
/**
 * SysRoleServiceImpl
 * Description：角色服务实现类
 *
 * @author tby
 * @date 2024-07-11 17:32:41
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Override
    public IPage<SysRoleRespVO> getPageList(SysRoleReqVO sysRoleReqVO) {
        // 分页设置
        Page<SysRole> page = MpQueryWrapperPageUtil.buildWrapperPage(new Page<>(), sysRoleReqVO);
        return baseMapper.getPageList(page, sysRoleReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysRoleRespVO add(SysRoleReqVO sysRoleReqVO) {
        // 新增和编辑逻辑相同的情况下 直接调用新增或编辑方法
        return this.addOrUpdate(sysRoleReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysRoleRespVO update(SysRoleReqVO sysRoleReqVO) {
        // 新增和编辑逻辑相同的情况下 直接调用新增或编辑方法
        return this.addOrUpdate(sysRoleReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysRoleRespVO addOrUpdate(SysRoleReqVO sysRoleReqVO) {
        Long sysRoleId = sysRoleReqVO.getId();
        if (sysRoleId != null){
            // 编辑
            SysRole sysRole = baseMapper.selectById(sysRoleId);
            Optional.ofNullable(sysRole).orElseThrow(() -> BizException.build("未找到要修改的角色信息"));
        }
        SysRole sysRole2Save = SysRole.convertFromReqVo(sysRoleReqVO);
        boolean success = this.saveOrUpdate(sysRole2Save);
        if (success) {
            return sysRole2Save.convertToRespVO();
        } else {
            BizException.throwException("操作失败，请刷新后重试");
        }
        return null;
    }

    @Override
    public SysRoleRespVO getDetailById(Long sysRoleId) {
        SysRole sysRole = baseMapper.selectById(sysRoleId);
        Optional.ofNullable(sysRole).orElseThrow(() -> BizException.build("未找到对应角色信息"));
        return sysRole.convertToRespVO();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(Long[] sysRoleIds) {
        if (sysRoleIds.length > 0) {
            this.removeByIds(Arrays.asList(sysRoleIds));
        }
    }
}
